package edu.nf.vac.admin.advice;

import edu.nf.vac.admin.vo.ResultVO;
import edu.nf.vac.auth.exception.AuthenticateException;
import edu.nf.vac.vaccination.exception.NeedleNumException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author : QYM
 * @create 2022/4/2
 * 全局异常处理
 */
@ControllerAdvice(basePackages = "edu.nf.vac.admin.controller")
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(AuthenticateException.class)
    @ResponseBody
    public ResultVO handleAuthException(AuthenticateException e){
        return response(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
    }

    @ExceptionHandler(NeedleNumException.class)
    @ResponseBody
    public ResultVO handleNeedleNumException(NeedleNumException e){
        return response(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultVO handleDataAccessException(RuntimeException e){
        log.error(e.getMessage(),e);
        return response(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器异常，请稍后重试！");
    }

    private ResultVO response(int code,String message){
        ResultVO vo = new ResultVO();
        vo.setCode(code);
        vo.setMessage(message);
        return vo;
    }
}
